package com.xinenhua.businessserver.personal;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kennyc.view.MultiStateView;
import com.oasis.oasislib.base.BaseFragmentActivity;
import com.oasis.oasislib.utils.DialogUtils;
import com.oasis.oasislib.utils.LogUtil;
import com.oasis.oasislib.utils.ToastUtils;
import com.oasis.oasislib.view.XListView;
import com.xinenhua.businessserver.Const;
import com.xinenhua.businessserver.R;
import com.xinenhua.businessserver.http.BaseHttp;

import org.apache.commons.lang3.StringUtils;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 虚拟客户资料(列表页面)
 */
@ContentView(R.layout.ficcustomerinfo)
public class FicCustomerInfo extends BaseFragmentActivity implements XListView.XListViewListener{

    @ViewInject(R.id.multiStateView)
    MultiStateView multiStateView ;

    @ViewInject(R.id.xlist_campaign)
    XListView xListView ;

    ArrayList<FicCustomerInfoPojo> list = new ArrayList<>() ;
    private boolean hasMoreData = true ;
    private int pageIndex = 1 ;

    @ViewInject(R.id.te3xtView5)
    EditText searchEditText;

    FicCustomerInfoAdapter adapter;

    String keyword="";

    @ViewInject(R.id.warpper_message)
    RelativeLayout warpper_message;

    @Override
    protected void start() {
        super.start();

        StatusBarCompat.setStatusBarColor(FicCustomerInfo.this, getResources().getColor(R.color.app_green));
        actionBar.hide();



        multiStateView.setViewState(MultiStateView.VIEW_STATE_LOADING);

        xListView.setPullLoadEnable(true);
        xListView.setPullRefreshEnable(true);
        xListView.setHeaderProgressDrawable(ContextCompat.getDrawable(context,R.mipmap.default_ptr_rotate));
        xListView.setRefreshTime();
        xListView.setPULL_LOAD_MORE_DELTA(60);
        xListView.setSCROLL_DURATION(400);
        xListView.setOFFSET_RADIO(3.0f);
        xListView.setXListViewListener(this);

        adapter = new FicCustomerInfoAdapter(FicCustomerInfo.this) ;
        adapter.setList(list);
        xListView.setAdapter(adapter);
        xListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final FicCustomerInfoPojo item = list.get(position-1);

                Intent openWelcomeActivityIntent=new Intent();
                Bundle bundle=new Bundle();
                bundle.putString("id",String.valueOf(item.getHtong_id()));

                openWelcomeActivityIntent.putExtras(bundle);
                openWelcomeActivityIntent.setClass(context, com.xinenhua.businessserver.entity.EntityCustomerInfo.class);
                startActivity(openWelcomeActivityIntent);
            }
        });

        getData();

        searchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

                    String key = searchEditText.getText().toString();
                    if(!StringUtils.isBlank(key)){
                        keyword = key;
                        onRefresh();
                    }else {
                        keyword = "";
                        onRefresh();
                    }
                    return true;
                }
                return false;
            }
        });

        warpper_message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    @Override
    public void onRefresh() {
        list.clear();
        pageIndex = 1 ;
        multiStateView.setViewState(MultiStateView.VIEW_STATE_LOADING);
        adapter.notifyDataSetChanged();
        getData();
    }

    @Override
    public void onLoadMore() {
        if (hasMoreData) {
            getData() ;
        }else {
            xListView.hideFooter();
        }
    }

    private void getData() {



        //type 虚拟客户：1 实体客户：2
        HashMap<String,String> map = new HashMap<>() ;
        map.put("list_rows",String.valueOf(Const.list_rows));
        map.put("page",String.valueOf(pageIndex));
        map.put("type","1");
        map.put("key",keyword);

        Call call = BaseHttp.getCallWithUrlAndData(Const.ServicememberInfo,map);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("Fail");

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String rr = new String(response.body().string());
                LogUtil.e(TAG,"-----"+rr);
                int result = BaseHttp.preResult(rr);
                if(result==BaseHttp.DATA_OK){
                    String s = BaseHttp.getJsonDataAsString(rr);
//                    JsonParser parser = new JsonParser();
//                    JsonObject asJsonObject = parser.parse(s).getAsJsonObject();
//                    String sign = asJsonObject.get("sign").getAsString();
                    final int total = BaseHttp.getJsonDataAsInt(s,"total") ;
                    int per_page = BaseHttp.getJsonDataAsInt(s,"per_page") ;
                    int current_page = BaseHttp.getJsonDataAsInt(s,"current_page") ;
                    int last_page = BaseHttp.getJsonDataAsInt(s,"last_page") ;
                    String jsonDataAsString = BaseHttp.getJsonDataAsString(s);

                    Gson gson = new Gson();
                    Type listType = new TypeToken<List<FicCustomerInfoPojo>>(){}.getType();
                    List<FicCustomerInfoPojo> customerlist = gson.fromJson(jsonDataAsString, listType);

                    pageIndex = current_page;

                    list.addAll(customerlist);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                            multiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);

                            xListView.setRefreshTime();
                            xListView.stopLoadMore();
                            xListView.stopRefresh();

                            if(list.size()<total){
                                hasMoreData = true ;
                            }else {
                                hasMoreData = false ;
                            }

                            if (hasMoreData) {
                                xListView.showFooter();
                            } else {
                                xListView.hideFooter();
                            }
                        }
                    });

                    System.out.println(s);
                    LogUtil.e(TAG,"--"+customerlist);

                }else {
                    ToastUtils.shortToast(context,BaseHttp.getJsonMsg(rr));

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                            multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);

                            xListView.setRefreshTime();
                            xListView.stopLoadMore();
                            xListView.stopRefresh();
                        }
                    });
                }

            }
        });

    }
}
